package com.car.rental.gateway.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
//import org.springframework.web.server.ServerWebExchangeUtils;
import reactor.core.publisher.Mono;
import java.net.URI;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

@Slf4j
@Component
@RequiredArgsConstructor
@Order(-1)
public class LoggingFilter implements GlobalFilter, Ordered {



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        
        log.info("请求进入网关 - 路径: {}, 方法: {}, 目标服务: {}", 
            path, 
            request.getMethod(),
            exchange.getAttribute(GATEWAY_ROUTE_ATTR)
        );
        
        // 记录请求头信息
        request.getHeaders().forEach((key, value) -> {
            log.info("请求头: {}={}", key, value);
        });
        
        // 记录路由信息
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        if (route != null) {
            log.info("路由信息: id={}, uri={}", route.getId(), route.getUri());
        }
        
        // 记录目标服务信息
        URI requestUrl = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
        if (requestUrl != null) {
            log.info("目标地址: {}", requestUrl);
        }

        return chain.filter(exchange)
            .then(Mono.fromRunnable(() -> {
                ServerHttpResponse response = exchange.getResponse();
                HttpStatus status = response.getStatusCode();
                log.info("响应状态: {}", status);
                
                // 记录响应头信息
                response.getHeaders().forEach((key, value) -> {
                    log.info("响应头: {}={}", key, value);
                });
                
                log.info("请求处理完成 - 路径: {}, 状态码: {}", path, status);
            }));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
} 